/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package com.ky.manage.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

import com.ky.manage.R;
import com.ky.manage.activity.SplashActivity;
import com.ky.manage.constant.OverallData;
import com.ky.manage.model.BaseEvent;
import com.ky.manage.utils.ToastUtils;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**基础android.support.v4.app.FragmentActivity，通过继承可获取或使用 里面创建的 组件 和 方法
 * *onFling内控制左右滑动手势操作范围，可自定义
 * @author Lemon
 * @see #mCurActivity
 * @see #mFragmentManager
 * @see #setContentView
 * @see #onDestroy
 * @use extends BaseActivity, 具体参考 .DemoActivity 和 .DemoFragmentActivity
 */
public abstract class BaseActivity extends FragmentActivity {
	private static final String TAG = "BaseActivity";

	public Activity getCurActivity() {
		return this; //必须return this;
	}

	/**
	 * 该Activity实例，命名为context是因为大部分方法都只需要context，写成context使用更方便
	 * @warn 不能在子类中创建
	 */
	protected BaseActivity mCurActivity = null;
	/**
	 * 布局解释器
	 * @warn 不能在子类中创建
	 */
	protected LayoutInflater mLayoutInflater = null;
	/**
	 * Fragment管理器
	 * @warn 不能在子类中创建
	 */
	protected FragmentManager mFragmentManager = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		mCurActivity = (BaseActivity) getCurActivity();
		mFragmentManager = getSupportFragmentManager();
		mLayoutInflater = getLayoutInflater();
		EventBus.getDefault().register(this);

		setContentView(getLayoutId());

		initView();
		initData();
	}

	protected abstract int getLayoutId();

	protected abstract void initView();

	protected abstract void initData();

	@TargetApi(Build.VERSION_CODES.KITKAT)
	@Override
	public void setContentView(int layoutResID) {
		super.setContentView(layoutResID);
		// 状态栏沉浸，4.4+生效 <<<<<<<<<<<<<<<<<
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			getWindow().setFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
			);
		}
		SystemBarTintManager tintManager = new SystemBarTintManager(this);
		tintManager.setStatusBarTintEnabled(true);
		if (mCurActivity instanceof SplashActivity) {
			tintManager.setStatusBarTintResource(R.color.white);//状态背景色，可传drawable资源
		} else {
			tintManager.setStatusBarTintResource(R.color.topbar_bg);//状态背景色，可传drawable资源
		}
		// 状态栏沉浸，4.4+生效 >>>>>>>>>>>>>>>>>
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onEventSubscribe(BaseEvent event) {

	}

	/**
	 * 用于 打开activity以及activity之间的通讯（传值）等；一些通讯相关基本操作（打电话、发短信等）
	 */
	protected Intent intent = null;

	/**
	 * 退出时之前的界面进入动画,可在finish();前通过改变它的值来改变动画效果
	 */
	protected int enterAnim = R.anim.fade;
	/**
	 * 退出时该界面动画,可在finish();前通过改变它的值来改变动画效果
	 */
	protected int exitAnim = R.anim.right_push_out;

	public <V extends TextView> V findTextView(int id, String text, OnClickListener listener) {
		V v = findView(id);
		v.setText(text);
		v.setOnClickListener(listener);
		return v;
	}

	public <V extends TextView> V findTextView(int id, String text) {
		return findTextView(id, text, null);
	}

	/**通过id查找并获取控件，使用时不需要强转
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <V extends View> V findView(int id) {
		return (V) findViewById(id);
	}
	/**通过id查找并获取控件，并setOnClickListener
	 * @param id
	 * @param l
	 * @return
	 */
	public <V extends View> V findView(int id, OnClickListener l) {
		V v = findView(id);
		v.setOnClickListener(l);
		return v;
	}
	/**通过id查找并获取控件，并setOnClickListener
	 * @param id
	 * @param l
	 * @return
	 */
	public <V extends View> V findViewById(int id, OnClickListener l) {
		return findView(id, l);
	}

	//启动新Activity方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

	/**打开新的Activity，向左滑入效果
	 * @param intent
	 */
	public void toActivity(Intent intent) {
		toActivity(intent, true);
	}
	/**打开新的Activity
	 * @param intent
	 * @param showAnimation
	 */
	public void toActivity(Intent intent, boolean showAnimation) {
		toActivity(intent, -1, showAnimation);
	}
	/**打开新的Activity，向左滑入效果
	 * @param intent
	 * @param requestCode
	 */
	public void toActivity(Intent intent, int requestCode) {
		toActivity(intent, requestCode, true);
	}
	/**打开新的Activity
	 * @param intent
	 * @param requestCode
	 * @param showAnimation
	 */
	public void toActivity(final Intent intent, final int requestCode, final boolean showAnimation) {
		OverallData.hd.post(()->{
			if (intent == null) {
				Log.w(TAG, "toActivity  intent == null >> return;");
				return;
			}
			//fragment中使用context.startActivity会导致在fragment中不能正常接收onActivityResult
			if (requestCode < 0) {
				startActivity(intent);
			} else {
				startActivityForResult(intent, requestCode);
			}
			if (showAnimation) {
				overridePendingTransition(R.anim.right_push_in, R.anim.hold);
			} else {
				overridePendingTransition(R.anim.null_anim, R.anim.null_anim);
			}
		});
	}

	/**一般用于对不支持的数据的处理，比如onCreate中获取到不能接受的id(id<=0)可以这样处理
	 */
	public void finishWithError(String error) {
		ToastUtils.showRoundRectToast(error);
		enterAnim = exitAnim = R.anim.null_anim;
		finish();
	}

	@Override
	public void finish() {
		super.finish();//必须写在最前才能显示自定义动画
		OverallData.hd.post(()->{
			if (enterAnim > 0 && exitAnim > 0) {
				try {
					overridePendingTransition(enterAnim, exitAnim);
				} catch (Exception e) {
				}
			}
		});
	}

	/**销毁并回收内存
	 * @warn 子类如果要使用这个方法内用到的变量，应重写onDestroy方法并在super.onDestroy();前操作
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();

		mLayoutInflater = null;
		mFragmentManager = null;
		intent = null;
		mCurActivity = null;
		EventBus.getDefault().unregister(this);
	}
}